package com.cgt.xiaotao.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgt.common.exception.BadRequestException;
import com.cgt.common.utils.UserContext;
import com.cgt.xiaotao.product.domain.dto.CartDTO;
import com.cgt.xiaotao.product.domain.po.Cart;
import com.cgt.xiaotao.product.domain.po.Product;
import com.cgt.xiaotao.product.domain.vo.CartVO;
import com.cgt.xiaotao.product.mapper.CartMapper;
import com.cgt.xiaotao.product.mapper.ProductMapper;
import com.cgt.xiaotao.product.service.ICartService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    private final ProductMapper productMapper;

    // 添加商品到购物车
    @Override
    @Transactional
    public void addCart(CartDTO dto) {
        // 获取用户id
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new BadRequestException("用户未登录");
        }

        // 查询购物车中是否已有该商品
        Cart existingCart = this.lambdaQuery()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, dto.getProductId())
                .list()
                .stream()
                .findFirst()
                .orElse(null);

        if (existingCart != null) {
            // 如果商品已存在，更新数量(在原有数量基础上增加)
            this.lambdaUpdate()
                    .eq(Cart::getUserId, userId)
                    .eq(Cart::getProductId, dto.getProductId())
                    .set(Cart::getQuantity, existingCart.getQuantity() + dto.getQuantity())
                    .set(Cart::getSelected, true)
                    .update();
        } else {
            // 如果商品不存在，添加新记录
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(dto.getProductId());
            cart.setQuantity(dto.getQuantity());
            cart.setSelected(true);
            this.save(cart);
        }
    }

    // 查询购物车列表
    @Override
    public List<CartVO> listCart() {
        // 获取用户id
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new BadRequestException("用户未登录");
        }
        // 查询购物车列表
        List<Cart> carts = this.lambdaQuery()
                .eq(Cart::getUserId, userId)
                .list();
        if (carts == null || carts.isEmpty()) {
            return new ArrayList<>();
        }

        // 收集所有商品ID
        List<Long> productIds = carts.stream()
                .map(Cart::getProductId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 批量查询商品信息
        List<Product> products = productMapper.selectBatchIds(productIds);
        Map<Long, Product> productMap = products.stream()
                .collect(Collectors.toMap(Product::getId, product -> product));

        // 构建返回结果
        List<CartVO> result = carts.stream()
                .map(cart -> {
                    Product product = productMap.get(cart.getProductId());
                    CartVO cartVO = new CartVO();
                    cartVO.setProductId(cart.getProductId());
                    cartVO.setQuantity(cart.getQuantity());
                    cartVO.setSelected(cart.getSelected());

                    // 如果商品存在，则填充商品信息
                    if (product != null) {
                        cartVO.setName(product.getName());
                        cartVO.setImageUrl(product.getImageUrl());
                        cartVO.setPrice(product.getPrice());
                    }
                    return cartVO;
                })
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public void updateCart(CartDTO dto) {
        // 获取用户id
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new BadRequestException("用户未登录");
        }

        // 根据条件更新
        boolean updated = this.lambdaUpdate()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, dto.getProductId())
                .set(Cart::getQuantity, dto.getQuantity())
                .set(Cart::getSelected, dto.getSelected())
                .update();

        if (!updated) {
            throw new BadRequestException("购物车中不存在该商品，更新失败！");
        }
    }

    @Override
    public void deleteCart(Long productId) {
        // 获取用户id
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new BadRequestException("用户未登录");
        }

        // 直接根据用户ID和商品ID删除购物车项
        boolean removed = this.remove(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, productId));

        if (!removed) {
            throw new BadRequestException("购物车中不存在该商品，删除失败！");
        }
    }
}
